<!--
 * @author tianchao
 组织角色定义
 -->
<template>
  <div id="organroledefine">
    <el-collapse-transition>
      <div v-show="searchshow" class="course-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input v-model.trim="listQuery.roleName" placeholder="角色名称搜索" class="search-input" @keyup.enter.native="handleFilter" />
        <div class="course-search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
          <span class="course-search-more" @click="searchshow = !searchshow">
            更多筛选条件
            <i class="el-icon-arrow-down" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <el-collapse-transition>
      <div v-show="!searchshow" class="course-search separate">
        <div class="course-search-inner">
          <el-row>
            <el-col :span="8">
              <div class="search-inner-item">
                <div class="item-label">角色名称</div>
                <el-input v-model.trim="search.roleName" style="width: 80%;" class="filter-item" placeholder="请输入角色名称搜索" />
              </div>
            </el-col>
            <el-col :span="8">
              <div class="search-inner-item">
                <div class="item-label">组织名称</div>
                <el-input v-model.trim="search.orgName" style="width: 80%;" class="filter-item" placeholder="请输入组织名称搜索" />
              </div>
            </el-col>
            <el-col :span="8">
              <div class="search-inner-item">
                <div class="item-label">状态</div>
                <el-checkbox-group v-model="search.roleStatus">
                  <el-checkbox key="ZT01" label="ZT01">启用</el-checkbox>
                  <el-checkbox key="ZT02" label="ZT02">禁用</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="course-search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
          <span class="course-search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <div class="btn-container">
      <div class="btn-container-title">
        <span>组织角色定义</span>
      </div>
      <div class="btn-container-btns">
        <el-button v-permission="'organroledefineInsert'" class="filter-item" style="margin-left: 10px;" @click="handleCreate">新建角色</el-button>
        <el-button v-permission="'organroledefineDeletes'" class="filter-item" style="margin-left: 10px;" @click="handleDeletes">批量删除</el-button>
      </div>
    </div>
    <div class="table">
      <el-table ref="rolemantable" v-loading="listLoading" :data="list" class="tableScope" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orgName" label="组织名称" show-overflow-tooltip width="200" />
        <el-table-column prop="roleName" label="角色名称" show-overflow-tooltip width="200" />
        <el-table-column prop="extend4" label="排序" show-overflow-tooltip width="100" />
        <el-table-column prop="extend1" label="描述" show-overflow-tooltip />
        <el-table-column prop="roleStatus" label="状态" width="80" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.roleStatus=='ZT01'?'启用':'禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="150" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-permission="'organroledefineUpdate'" type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button v-permission="'organroledefineDelete'" type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            <el-button v-permission="'organroledefinePermission'" type="text" size="mini" @click="handlePower(scope.row)">权限分配</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="btn-pagion fix">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" center width="450px">
      <el-form ref="dataForm" v-loading="formloading" :model="temp" :rules="rules" class="dataForm" label-position="right" label-width="80px" style="height:370px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="temp.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="选择组织" prop="orgId">
          <el-button @click="OpenOrgTreedialog">{{ selectOrgTree[0].orgName || '请选择组织' }}</el-button>
        </el-form-item>
        <el-form-item label="状态" prop="roleStatus">
          <el-radio-group v-model="temp.roleStatus">
            <el-radio label="ZT01">启用</el-radio>
            <el-radio label="ZT02">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序号" prop="extend4">
          <el-input v-model.trim="temp.extend4" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model.trim="temp.extend1" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="dialogFormVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :title="dialogPowertitle" :visible.sync="dialogPowerVisible" center width="450px">
      <span>所属系统：</span>
      <el-select v-model="belongSystem" placeholder="请选择" @change="changeSys">
        <el-option v-for="item in CDFLMC" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" />
      </el-select>
      <power-tree ref="childTree" :sys-id="belongSystem" :role-id="roleId" @dialogPower="dialogPower" />
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="dialogPowerVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="saveData">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" title="选择组织" :visible.sync="OrgTreedialog" width="480px" center>
      <org-tree ref="showOrgTree" @selectOrgTree="selectOrg" />
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="OrgTreedialog = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="saveOrg">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { specialText } from '@/utils/validate'
import { roleList, deleteRole, updateRole, createRole, getDictByCode } from '@/views/organroledefine/api/index'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import PowerTree from '@/views/organroledefine/components/PowerTree' // Secondary package based on el-pagination
import OrgTree from '@/views/organroledefine/components/orgtree' // Secondary package based on el-pagination
import permission from '@/directive/permission/index.js' // 权限判断指令
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui

export default {
  name: 'Organroledefine',
  components: { Pagination, PowerTree, OrgTree },
  directives: { permission, elDragDialog },
  data() {
    return {
      OrgTreedialog: false,
      formloading: false,
      listQuery: {
        page: 1,
        limit: 10,
        roleName: ''
      },
      searchshow: true,
      search: {
        roleName: '',
        roleStatus: [],
        orgName: ''
      },
      list: [],
      total: 0,
      dialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        create: '新增角色',
        update: '编辑角色'
      },
      multipleSelection: [],
      listLoading: false,
      temp: {
        roleName: '',
        extend4: '',
        roleStatus: 'ZT01',
        roleType: 'JSLX02',
        extend1: '',
        orgId: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请填写角色名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' }
        ],
        roleStatus: [{ required: true, message: '请选择角色状态', trigger: 'change' }],
        orgId: [{ required: true, message: '请选择组织', trigger: 'change' }]
      },
      dialogPowertitle: '权限分配',
      dialogPowerVisible: false, // 权限树
      roleId: '',
      dicListJSLX: [], // 角色类型
      CDFLMC: [],
      belongSystem: '',
      temporaryOrg: '',
      selectOrgTree: [{}]// 回显组织
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.getList()

    this.getDicCDFLMC()
  },
  methods: {
    /**
     * 获取字典--角色类型
     */
    getDic() {
      return new Promise((resolve, reject) => {
        getDictByCode('JSLX').then(response => {
          this.dicListJSLX = (response.data.data && response.data.data.length > 0) ? response.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },
    changeSys(val) {
      this.$refs.childTree.test(val)
    },
    /**
    * 获取字典--所属系统
    */
    getDicCDFLMC() {
      return new Promise((resolve, reject) => {
        getDictByCode('CDFLMC').then(response => {
          this.CDFLMC = (response.data.data && response.data.data.length > 0) ? response.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },
    saveData() {
      this.$refs.childTree.saveData()
    },
    /**
     * 关闭权限弹框
     */
    dialogPower(val) {
      this.dialogPowerVisible = val
    },
    /**
     * 权限分配
     */
    handlePower(val) {
      this.roleId = val.id
      this.dialogPowerVisible = true
    },
    getList(obj) {
      this.listLoading = true
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit
      }
      if (this.searchshow) {
        query['roleName'] = this.listQuery.roleName
      } else {
        query['roleName'] = this.search.roleName
        query['orgName'] = this.search.orgName
        if (this.search.roleStatus.length > 0) {
          query['roleStatus'] = this.search.roleStatus.join(',')
        } else {
          query['roleStatus'] = ''
        }
      }
      return new Promise((resolve, reject) => {
        roleList(query).then(response => {
          this.list = response.data.data.rows
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },

    resetTemp() {
      this.temp = {
        roleName: '',
        extend1: '',
        extend4: '',
        roleStatus: 'ZT01',
        roleType: 'JSLX02',
        orgId: ''
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resettingBtn() {
      this.listQuery.roleName = ''
      for (const i in this.search) {
        if (i === 'roleStatus') {
          this.search['' + i + ''] = []
        } else {
          this.search['' + i + ''] = ''
        }
      }
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.selectOrgTree = [{}]
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    handleDeletes() {
      if (this.multipleSelection.length > 0) {
        this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const arr = []
          this.multipleSelection.forEach(item => {
            arr.push(item.id)
          })
          const ids = arr.join(',')
          this.deleteRole(ids)
        }).catch(() => { })
      } else {
        this.$message({
          message: '请选择需要删除的数据！',
          type: 'warning'
        })
      }
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRole(row.id)
      }).catch(() => { })
    },
    deleteRole(ids) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      deleteRole(ids).then(() => {
        loading.close()
        this.$message({
          message: '删除成功！',
          type: 'success'
        })
        this.getList()
      })
    },
    /*
    * 添加
    * */
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          var arr = this.selectOrgTree
          var orglist = []
          if (arr.length > 0) {
            arr.forEach(item => {
              var obj = {
                name: item.orgName,
                id: item.id,
                objectType: item.orgType
              }
              orglist.push(obj)
            })
          } else {
            this.$message({
              message: '请选择组织！',
              type: 'warning'
            })
            return false
          }
          this.temp['orgId'] = orglist[0].id
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          return new Promise((resolve, reject) => {
            createRole(this.temp).then(() => {
              loading.close()
              this.dialogFormVisible = false
              this.$message({
                message: '创建成功！',
                type: 'success'
              })
              this.getList()
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },
    /*
    * 编辑
    * */
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      const extend = this.temp.orgId ? { orgId: this.temp.orgId, orgName: this.temp.orgName } : ''
      const tmp = []
      tmp.push(extend)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        console.log(tmp)
        this.selectOrgTree = tmp
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          console.log(this.selectOrgTree)
          var arr = this.selectOrgTree
          var orglist = []
          if (arr.length > 0) {
            arr.forEach(item => {
              var obj = {
                name: item.orgName,
                id: item.id || item.orgId,
                objectType: item.orgType
              }
              orglist.push(obj)
            })
          } else {
            this.$message({
              message: '请选择组织！',
              type: 'warning'
            })
            return false
          }
          tempData['orgId'] = orglist[0].id
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          return new Promise((resolve, reject) => {
            updateRole(tempData).then(() => {
              loading.close()
              this.dialogFormVisible = false
              this.$message({
                message: '更新成功！',
                type: 'success'
              })
              this.getList()
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },
    handleSelectionChange(arr) {
      this.multipleSelection = arr
    },
    /*
    * 打开组织树
    * */
    OpenOrgTreedialog() {
      this.OrgTreedialog = true
      this.$nextTick(() => {
        this.$refs.showOrgTree.clearSearchTree()
        this.$refs.showOrgTree.selectData = this.selectOrgTree[0].orgId || this.selectOrgTree[0].id
        this.$refs.showOrgTree.echo()
      })
    },
    selectOrg(val) {
      console.log(val)
      this.temporaryOrg = [val]
    },
    /*
    * 确定组织
    * */
    saveOrg() {
      this.OrgTreedialog = false
      this.temp.orgId = this.temporaryOrg[0].id
      console.log(this.temporaryOrg)
      this.selectOrgTree = this.temporaryOrg
    }

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
#organroledefine {
  padding: 10px;
  .course-search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 20px;
      }
    }
    .search-input {
      width: 60%;
      position: relative;
      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .course-search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .course-search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }
    &.merge {
      height: 50px;
      line-height: 50px;
    }
    &.separate {
      .course-search-inner {
        padding-top: 10px;
        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }
          .el-input {
            position: relative;
            .el-input__inner {
              border: none;
              padding: 0;
            }
            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
          .el-checkbox-group {
            height: 36px;
            line-height: 36px;
          }
        }
      }
      .course-search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }
  .btn-container {
    display: flex;
    align-items: center;
    margin-top: 5px;
    margin-bottom: 5px;
    .btn-container-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: 600;
      color: rgba(51, 51, 51, 1);
    }
  }
}
</style>

